package util;

import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ConfigHandler {
	
//	private static final String CONFIG = "C:\\Users\\sarala.EBI\\ideaprojects\\restjson\\ws\\web\\WEB-INF\\resources\\config.xml";
	private static final String CONFIG = "/home/sarala/ricordoeu/ricordows/resources/config.xml";
	public static final String RICORDOID="ricordoid";

	private static Document document = null;
	private static Transformer transformer = null;
	
	public static void setupConfigHandler(){
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();			
			document = db.parse(CONFIG);
			
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
	        transformer = transformerFactory.newTransformer();	        
		} catch (SAXException e) {		
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		}
	}

	public static String readAndUpdate(String elementId){
        if(document==null){
            setupConfigHandler();
        }

        //read ricordo element id
        NodeList nodeLst = document.getElementsByTagName(elementId);
        Element fstNmElmnt = (Element) nodeLst.item(0);
        NodeList fstNm = fstNmElmnt.getChildNodes();
		Node node = ((Node) fstNm.item(0));

        //increamet recordo id
		String value = node.getNodeValue();
		node.setNodeValue(""+(Integer.parseInt(value)+1));

        //update the config file
		DOMSource source = new DOMSource(document);
        StreamResult result =  new StreamResult(CONFIG);
        try {
			transformer.transform(source, result);
		} catch (TransformerException e) {
			e.printStackTrace();
		}

        //retrun the new recordo id
		return value;
	}
}
